<template>
  <div style="padding: 40px">
    <div style="margin: 10px 0;">
      <el-button type="primary" style="margin-left: 10px;" @click="add">发布预约</el-button>
    </div>


    <el-table :data="tableData" border stripe style="width: 100%;">
      <el-table-column type="index" label="通知ID" width="100px" />
      <el-table-column label="宠物" >
        <template #default="scope">
          {{ petFormat(scope.row.petId) }}
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描  述" />
     
      <el-table-column prop="status" label="状态"  width="100px" >
        <template #default="scope">
          <el-tag v-if="scope.row.status === -1" type="info">审核中</el-tag>
          <el-tag v-else-if="scope.row.status === -2" type="danger">未通过审核</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="primary">已预约</el-tag>
          <el-tag v-else-if="scope.row.status === 0" >未预约</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="success">已完成</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="userName" label="费用">
        <template #default="scope">
          {{ scope.row.price }}-支付豆
        </template>
      </el-table-column>
      <el-table-column  label="地址信息" width="300px">
        <template #default="scope">
          {{ addressFormat(scope.row.addressId)  }}
        </template>
      </el-table-column>
      <el-table-column label="开始时间">
        <template #default="scope">
          {{ timeFormat(scope.row.appointmentStartTime) }}
        </template>
      </el-table-column>
      <el-table-column label="结束时间">
        <template #default="scope">
          {{ timeFormat(scope.row.appointmentEndTime) }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="250px">
        <template #default="scope">
          <el-button type="primary" v-if="scope.row.status === -2"    @click="handleEdit(scope.row)">联系管理员</el-button>
         <div v-if="scope.row.status === 1">
          <el-button type="success" @click="handleFinish(scope.row)">帮助完成</el-button>
          <el-button style="background-color: #f6f2f2;" @click="handleCustomer(scope.row)">联系他</el-button>
         </div>
        </template>

      </el-table-column>
    </el-table>

    <!-- 新增弹窗 -->
    <el-dialog :visible.sync="dialogVisible" title="新增预约" width="50%" @close="handleClose">
      <el-form :model="form" label-width="160px" ref="validateFormRef">
        <el-form-item label="选择地址" prop="addressId">
          <el-select v-model="form.addressId" placeholder="请选择">
            <el-option v-for="item in addressList" :key="item.address" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择宠物" prop="petId">
          <el-select v-model="form.petId" placeholder="请选择">
            <el-option v-for="item in petList" :key="item.petId" :label="item.petName" :value="item.petId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="appointmentStartTime">
          <el-date-picker v-model="form.appointmentStartTime" type="datetime" placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="结束时间" prop="appointmentEndTime">
          <el-date-picker v-model="form.appointmentEndTime" type="datetime" placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="描  述" prop="description">
          <el-input v-model="form.description" style="width: 50%"></el-input>
        </el-form-item>
        <el-form-item label="支付价格（支付豆）" prop="price">
          <el-input-number v-model="form.price"  :step="10" :min="1" label="价格"></el-input-number>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-pagination class="page" @current-change="handleCurrentChange" :current-page.sync="currentPage" background
      :page-size="10" layout="prev, pager, next, jumper" :total="total">
    </el-pagination>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getAppointment,getAppointmentMyList,
  getAppointmentReserveFinish
} from '@/http/appointment.js'
import { getAddressList } from '@/http/address'
import { PostPetList } from '@/http/pet.js'
export default {
  data() {
    return {
      form: {
        addressId: null,
        appointmentEndTime: "",
        appointmentStartTime: "",
        description: "",
        price: 1,
        petId: null,
      },
      form1: {
        appointmentId: null,
        reviewComment: null,
        status: null
      },
      dialogVisible: false,
      dialogVisible1: false,
      dialogVisible2: false,
      currentPage: 1,
      tableData: [],
      total: 1,
      addressList: [],
      petList : [],
      title: '添加预约',
    }

  },
  created() {
    this.load()
  },

  methods: {
    handleCustomer(row){
      // 发送方id、 接收方id、 消息内容、 发送方姓名、 接收方姓名
      this.$router.push({
        path: '/chat',
        query: {
          sendId : this.userId,
          redaId : row.providerId,
          sendName: row.publisherName,
          redaName: row.providerName,
        }
      })
    },
    handleFinish(row) {
      this.$confirm('确定完成预约吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const {message,code} = await getAppointmentReserveFinish({
          appointmentId: row.appointmentId,
          publishId: row.publisherId,
        })
        if (code == 0) {
          this.$message.success('预约完成')
          this.load()
        } else {
          this.$message.error(message)
        }
        
      })
    },
    timeFormat(time) {
      const date = new Date(time);

      // 获取年、月、日、小时和分钟
      const year = date.getUTCFullYear();
      const month = date.getUTCMonth() + 1; // getUTCMonth() 返回 0-11，所以需要加 1
      const day = date.getUTCDate();
      const hours = date.getUTCHours();
      const minutes = date.getUTCMinutes();

      // 构建格式化的字符串
      return `${year}年${month}月${day}日${hours}点${minutes}分`;
    },
    addressFormat(id) {
      if (id == null) {
        return '未设置地址'
      }
      const address = this.addressList.find(item => {
        if (item.value === id) {
          return item
        }
      })
      return address.label
    },
    petFormat(id) {
      if (id  == null) {
        return '未设置宠物'
      }
      const pet = this.petList.find(item => item.petId === id)
      return pet ? pet.petName : '未设置宠物'
    },
    handleClose() {
      this.$refs['validateFormRef'].resetFields()
      this.dialogVisible = false
    },
    async load() {
      let res = null
      const res1 =  await getAddressList()
      const res2 = await PostPetList({
        current: 1,
        size: 1000
      })
      res1.data.forEach(element => {
        let address = JSON.parse(element.address)
        this.addressList.push({
          label: `省：${address.province || ''}，市：${address.city|| ''}，区：${address.area|| ''}，详细地址：${address.detailAddress || ''}，电话：${address.phone || ''}，姓名：${address.name || ''}`,
          value: element.addressId
        })
      });
      this.petList = res2.data.records
     
        res = await getAppointmentMyList({
          current: this.currentPage,
          "pageSize": 10,
        })
      

      this.tableData = res.data.records
      this.total = Number(res.data.total)
    },
    add() {
      this.title = '添加预约',
      this.dialogVisible = true
    },
    // 编辑
    handleEdit(row) {
      this.title = '编辑预约',
      this.form = { ...row }
      this.dialogVisible = true
    },
    // 添加
    async save() {
      const { code, message } = await getAppointment(this.form)
      if (code == '0') {
        this.$message({
          type: "success",
          message: "添加成功"
        })
      } else {
        this.$message({
          type: "error",
          message: "添加失败"
        })
      }
      this.dialogVisible = false
      this.load()
    },
    async handleDelete(id) {
      console.log(id);

      const { code, message } = await getCategoriesDelete({ id: id })
      if (code == '0') {
        this.$message({
          type: "success",
          message: "删除成功"
        })
      } else {
        this.$message({
          type: "error",
          message: message
        })
      }
      this.load()  // 删除之后重新加载表格的数据
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load()

    },
    handleCurrentChange(pageNum) {
      this.currentPage = pageNum
      this.load()
    },
    onDaloag(row) {
      this.form1 = row
      this.dialogVisible2 = true
    }
  },
  computed: {
    ...mapGetters({
      userId: 'user/getUserId'
    })
  }

}
</script>

<style></style>